require "digest/sha1"

class Administrator < ActiveRecord::Base
  
  validates_uniqueness_of :username, :on => :save, :message => "管理员名不能重复"
  validates_presence_of :password, :message => "必须填写管理员密码"
  
  def before_create
    self.last_login_time = Time.now
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    self.hashed_password = Administrator.hash_password(@password)
  end
  
  def name
    self.username
  end
  
  def self.login(username, password)
    hashed_password = hash_password(password || "")
    find(:first, :conditions => ["username = ? AND hashed_password = ?", username, hashed_password])
  end
  
  private
  def self.hash_password(password)
    Digest::SHA1.hexdigest(password)
  end
end
